package com.zj.syzs.fragment;


import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zj.shouyou.R;
import com.zj.syzs.adapter.Mobile_Web_Adapter;
import com.zj.syzs.bean.GiftBean;
import com.zj.syzs.config.UrlConfig;
import com.zj.syzs.ui.GiftInfoActivity;
import com.zj.syzs.utils.HttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class MobGameFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2<ListView>, AdapterView.OnItemClickListener {
    private PullToRefreshListView ptrListView;
    private List<GiftBean> list = new ArrayList<>();
    private Mobile_Web_Adapter adapter;
    private int page = 1;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mobile_game, container, false);
        initView(view);
        initData();
        return view;
    }

    private void initView(View view) {
        // listview + adapter + 数据源
        ptrListView = (PullToRefreshListView) view.findViewById(R.id.fragment_gift_mobile_listview);
        //刷新模式
        ptrListView.setMode(PullToRefreshBase.Mode.BOTH);
        ptrListView.setOnRefreshListener(this);
        ptrListView.setOnItemClickListener(this);
        ptrListView.setShowIndicator(true);
        adapter = new Mobile_Web_Adapter(list, getActivity());
        ptrListView.setRefreshing();
        // 刷新时间
        String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
                | DateUtils.FORMAT_ABBREV_ALL);
        // 设置刷新时候的字体
        ptrListView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        ptrListView.setAdapter(adapter);
    }

    private void initData() {
        new LoadGiftTask().execute(UrlConfig.GIFT_URL);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        ILoadingLayout iLoadingLayout = refreshView.getLoadingLayoutProxy();
        String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(),
                DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
        //设置刷新的标签
        iLoadingLayout.setLastUpdatedLabel(label);
        page = 1;
        initData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        page++;
        if (page == 32) {
            ptrListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }
        initData();
    }

    //传递ID,跳转到info页面
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(getActivity(), GiftInfoActivity.class);
        intent.putExtra("id",""+list.get(position-1).getId());
        startActivity(intent);
    }

    /**
     * 第一步 继承AsyncTask
     * 第二步 重写doInBackground方法
     * Thread + Hanlder
     */
    private class LoadGiftTask extends AsyncTask<String, Void, List<GiftBean>> {
        @Override
        protected List<GiftBean> doInBackground(String... params) {
            HashMap<String, String> map = getMap();
            try {
                String jsonResult = HttpUtils.post(params[0], map);
                String state = new JSONObject(jsonResult).optString("state");
                if ("success".equals(state)) {
                    JSONArray arr = new JSONObject(jsonResult).getJSONArray("info");
                    List<GiftBean> giftBeans = JSON.parseArray(arr.toString(), GiftBean.class);
                    return giftBeans;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        private HashMap<String, String> getMap() {
            HashMap<String, String> params = new HashMap<>();
            params.put("uid", "");
            params.put("token", "78fc45f6f%2C7%2C9");
            params.put("platform", "2");
            params.put("gifttype", "1");
            params.put("page", page + "");
            return params;
        }

        //  handler代码
        @Override
        protected void onPostExecute(List<GiftBean> giftBeans) {
            super.onPostExecute(giftBeans);
            if (giftBeans != null && !giftBeans.isEmpty()) {
                if (page == 1 && !list.isEmpty()) {
                    list.clear();
                }
                list.addAll(giftBeans);
                adapter.notifyDataSetChanged();
                ptrListView.onRefreshComplete();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


}
